import java.awt.Choice;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import javax.swing.JCheckBox;

public class GUIPanel1 extends JPanel {
	/* Write the serializable ID */
	private static final long serialVersionUID = 1L;

	/* All the textfields */
	private JTextField txtTrainName, txtSourceStation, txtDestinationStation,
			txtTrainCode;

	/* All the labels */
	private JLabel lblTrain, lblTrainName, lblDestinationStation,
			lblSourceStation, lblTrainCode, lblIntermediateStation,
			lblArrivalTime, lblDepartureTime, lblSourceDepartureTime,
			lblDestinationArrivalTime, lblDays, lblTimeDifference;

	/* All the buttons */
	private JButton btnAddTrain, btnDisplayTrains, btnAddIntermediateStation;

	/* All the choices */
	Choice chSourceDepartureTimeHours, chTimeDifference;
	private Choice chSourceDepartureTimeMinutes, chSourceStation;

	/* Checkboxes */
	private JCheckBox cbTues, cbWed, cbThurs, cbFri, cbMon, cbSat, cbSun;

	/* Object to access the methods of Location Class */
	Location location;

	/* The four hashmaps for storing the trains and stations and the trains */
	HashMap<Integer, Station> stationGraph;
	HashMap<Integer, Train> trainGraph;
	HashMap<Integer, Track> trackGraph;
	/*
	 * The instance of database through which we can do the store and load
	 * operations
	 */
	ObjectContainer db;
	Station st;
	Train train;
	Track track;
	private JTextField txtIntermediatestation;
	private JButton btnClear;
	/* Populatedatabase variable to access the methods */
	PopulateDatabase p;
	int enable;
	/* For intermediate Stations */
	ArrayList<Integer> listOfStationsAdded;
	/* Arraylist for arrival times */
	ArrayList<String> listOfArrivalTimes;
	/* Arraylist for departure times */
	ArrayList<String> listOfDepartureTimes;
	/* Arraylist for running days of the train */
	ArrayList<String> runningDaysOfTheWeek;
	ArrayList<String> tempVariableForStoringDays;

	private JButton btnFinish;
	private Choice chDestinationArrivalTimeHours;
	private Choice chDestinationArrivalTimeMinutes;
	private Choice chArrivalTimeHours;
	private Choice chArrivalTimeMinutes;
	private Choice chDepartureTimeHours;
	private Choice chDepartureTimeMinutes;
	private Choice chDestinationStation;
	private Choice chIntermediateStation;

	private GUIPanel1 guiPanel1;
	private ArrayList<Integer> stations;

	/* Constructor */
	public GUIPanel1(ArrayList<Integer> stations) {
		stationGraph = new HashMap<Integer, Station>();
		trainGraph = new HashMap<Integer, Train>();
		trackGraph = new HashMap<Integer, Track>();
		location = new Location();
		listOfStationsAdded = new ArrayList<Integer>();
		listOfArrivalTimes = new ArrayList<String>();
		listOfDepartureTimes = new ArrayList<String>();
		runningDaysOfTheWeek = new ArrayList<String>();
		tempVariableForStoringDays = new ArrayList<String>();
		setStations(stations);
		try {
			p = new PopulateDatabase();
		} catch (Exception e) {
			e.printStackTrace();
		}

		populateHashMaps();

		createPanel();
		textBoxesEventHandling();
		buttonEventHandling();
		addComponents();
		/* 0 is for AddtrainButton and 1 is for AddIntermedateTrain Button */
		enable = 1;
		initializeStationList();
	}

	private void initializeStationList() {
		// adding source station
		txtSourceStation.setText(String.valueOf(stations.get(0)));
		txtSourceStation.setEnabled(false);

		// adding Destination station
		txtDestinationStation.setText(String.valueOf(stations.get(stations
				.size() - 1)));
		txtDestinationStation.setEnabled(false);
		// adding Intermediate station
		if (stations.size() > 2)
			txtIntermediatestation.setText(String.valueOf(stations.get(1)));

	}

	public void openDatabase() {
		db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),
				"Routing Management System");
	}

	public void closeDatabase() {
		db.close();
		db = null;
	}

	/* It will retrieve the train object from the database as per the Train code */
	Train retrieveTrainObject(final int trainCode) {
		/* Code to retrieve a particular object */
		@SuppressWarnings("serial")
		List<Train> train = db.query(new Predicate<Train>() {
			public boolean match(Train train) {
				return train.getTrainCode() == trainCode;
			}
		});
		if (train.size() == 0) {
			return null;
		} else {
			Train tr = train.get(0);
			return tr;
		}
	}

	void populateHashMaps() {
		openDatabase();
		/* Code to populate the hash map for stations */
		@SuppressWarnings("serial")
		List<Station> stationList = db.query(new Predicate<Station>() {
			public boolean match(Station station) {
				return station.getStationCode() > 0;
			}
		});
		for (Station station : stationList) {
			stationGraph.put(station.getStationCode(), station);
		}
		/* Code to populate the hash map for trains */
		@SuppressWarnings("serial")
		List<Train> trainList = db.query(new Predicate<Train>() {
			public boolean match(Train train) {
				return train.getTrainCode() > 0;
			}
		});
		for (Train train : trainList) {
			trainGraph.put(train.getTrainCode(), train);
		}

		/* Code to populate the hash map for tracks */
		@SuppressWarnings("serial")
		List<Track> trackList = db.query(new Predicate<Track>() {
			public boolean match(Track track) {
				return track.getTrackCode() > 0;
			}
		});
		for (Track track : trackList) {
			trackGraph.put(track.getTrackCode(), track);
		}
		closeDatabase();
	}

	Station retrieveStationObject(final int stationCode) {

		/* Code to retrieve a particular object */
		@SuppressWarnings("serial")
		List<Station> station = db.query(new Predicate<Station>() {
			public boolean match(Station station) {
				return station.getStationCode() == stationCode;
			}
		});
		// JOptionPane.showMessageDialog(null, "The size of the station = "
		// +station.size());
		Station st = station.get(0);
		return st;
	}

	Track retrieveTrackObject(final int station1, final int station2) {
		@SuppressWarnings("serial")
		List<Track> track1 = db.query(new Predicate<Track>() {
			public boolean match(Track track) {
				return track.getNextStation() == station1
						&& track.getPrevStation() == station2;
			}
		});
		if (track1.size() != 0) {
			Track tr = track1.get(0);
			return tr;
		} else
			return null;
	}

	void insertIntoDatabase(Object object) {
		db.store(object);
	}

	void deleteFromDatabase(Object object) {
		db.delete(object);
	}

	private void createPanel() {
		setBackground(UIManager.getColor("Button.select"));
		setLayout(null);

		lblTrain = new JLabel("TRAIN");
		lblTrain.setBounds(291, 29, 70, 15);

		/* For the Train */
		lblTrainName = new JLabel("Train Name");
		lblTrainName.setBounds(263, 153, 114, 15);

		txtTrainName = new JTextField();
		txtTrainName.setBounds(250, 174, 114, 19);

		txtTrainName.setColumns(10);

		lblSourceStation = new JLabel("Source Station");
		lblSourceStation.setBounds(263, 199, 114, 15);

		txtSourceStation = new JTextField();
		txtSourceStation.setBounds(247, 219, 130, 19);

		txtSourceStation.setColumns(10);

		lblDestinationStation = new JLabel("Destination Station");
		lblDestinationStation.setBounds(250, 294, 143, 15);

		txtDestinationStation = new JTextField();
		txtDestinationStation.setBounds(250, 321, 143, 19);

		txtDestinationStation.setColumns(10);

		lblTrainCode = new JLabel("Train Code");
		lblTrainCode.setBounds(263, 94, 98, 15);

		txtTrainCode = new JTextField();
		txtTrainCode.setBounds(250, 120, 143, 21);

		txtTrainCode.setColumns(10);

		btnAddTrain = new JButton("Add Train");

		btnAddTrain.setBounds(372, 651, 117, 25);

		btnDisplayTrains = new JButton("Display Trains");
		btnDisplayTrains.setBounds(372, 697, 143, 25);

		lblIntermediateStation = new JLabel("Intermediate Station 1");
		lblIntermediateStation.setBounds(248, 408, 178, 15);

		txtIntermediatestation = new JTextField();
		txtIntermediatestation.setText("");
		txtIntermediatestation.setBounds(250, 429, 143, 19);
		txtIntermediatestation.setColumns(10);

		btnAddIntermediateStation = new JButton("Add Intermediate Station");
		btnAddIntermediateStation.setBounds(225, 614, 238, 25);

		btnClear = new JButton("Clear");
		btnClear.setBounds(199, 697, 130, 28);

		btnFinish = new JButton("Finish");
		btnFinish.setBounds(202, 651, 117, 25);

		lblArrivalTime = new JLabel("Arrival Time");
		lblArrivalTime.setBounds(250, 460, 143, 15);

		lblDepartureTime = new JLabel("Departure Time");
		lblDepartureTime.setBounds(250, 508, 143, 15);

		lblSourceDepartureTime = new JLabel("Source Departure Time");
		lblSourceDepartureTime.setBounds(250, 250, 176, 15);

		lblDestinationArrivalTime = new JLabel("Destination Arrival time");
		lblDestinationArrivalTime.setBounds(250, 352, 213, 15);

		chSourceDepartureTimeHours = new Choice();
		chSourceDepartureTimeHours.setBounds(260, 271, 43, 21);
		for (int i = 0; i < 24; i++)
			chSourceDepartureTimeHours.add(String.valueOf(i));

		chSourceDepartureTimeMinutes = new Choice();
		chSourceDepartureTimeMinutes.setBounds(350, 271, 43, 21);
		for (int i = 0; i < 60; i++)
			chSourceDepartureTimeMinutes.add(String.valueOf(i));

		chDestinationArrivalTimeHours = new Choice();
		chDestinationArrivalTimeHours.setBounds(263, 373, 43, 21);
		for (int i = 0; i < 24; i++)
			chDestinationArrivalTimeHours.add(String.valueOf(i));

		chDestinationArrivalTimeMinutes = new Choice();
		chDestinationArrivalTimeMinutes.setBounds(350, 373, 43, 21);
		for (int i = 0; i < 60; i++)
			chDestinationArrivalTimeMinutes.add(String.valueOf(i));

		chArrivalTimeHours = new Choice();
		chArrivalTimeHours.setBounds(263, 481, 43, 21);
		for (int i = 0; i < 24; i++)
			chArrivalTimeHours.add(String.valueOf(i));

		chArrivalTimeMinutes = new Choice();
		chArrivalTimeMinutes.setBounds(350, 481, 43, 21);
		for (int i = 0; i < 60; i++)
			chArrivalTimeMinutes.add(String.valueOf(i));

		chDepartureTimeHours = new Choice();
		chDepartureTimeHours.setBounds(263, 529, 43, 21);
		for (int i = 0; i < 24; i++)
			chDepartureTimeHours.add(String.valueOf(i));

		chDepartureTimeMinutes = new Choice();
		chDepartureTimeMinutes.setBounds(350, 529, 43, 21);
		for (int i = 0; i < 60; i++)
			chDepartureTimeMinutes.add(String.valueOf(i));

		cbTues = new JCheckBox("Tues");
		cbTues.setBounds(187, 583, 60, 23);

		cbWed = new JCheckBox("Wed");
		cbWed.setBounds(249, 583, 70, 23);

		cbThurs = new JCheckBox("Thurs");
		cbThurs.setBounds(323, 583, 70, 23);

		cbFri = new JCheckBox("Fri");
		cbFri.setBounds(408, 583, 55, 23);

		cbMon = new JCheckBox("Mon");
		cbMon.setBounds(124, 583, 55, 23);

		cbSat = new JCheckBox("Sat");
		cbSat.setBounds(476, 583, 55, 23);

		cbSun = new JCheckBox("Sun");
		cbSun.setBounds(546, 583, 55, 23);

		lblDays = new JLabel("Days");
		lblDays.setBounds(291, 556, 70, 15);

		chSourceStation = new Choice();
		chSourceStation.setBounds(28, 618, 98, 21);
		for (Integer var : getStationGraph().keySet()) {
			chSourceStation.add(getStationGraph().get(var).getStationName());
		}

		chDestinationStation = new Choice();
		chDestinationStation.setBounds(28, 657, 98, 19);
		for (Integer var : getStationGraph().keySet()) {
			chDestinationStation.add(getStationGraph().get(var)
					.getStationName());
		}

		chIntermediateStation = new Choice();
		chIntermediateStation.setBounds(28, 697, 98, 21);
		for (Integer var : getStationGraph().keySet()) {
			chIntermediateStation.add(getStationGraph().get(var)
					.getStationName());
		}

		chTimeDifference = new Choice();
		chTimeDifference.setBounds(546, 697, 70, 21);
		for (int i = 10; i <= 60; i = i + 10)
			chTimeDifference.add(String.valueOf(i));
		chTimeDifference.select(2);

		lblTimeDifference = new JLabel("Time difference");
		lblTimeDifference.setBounds(531, 656, 112, 15);

	}

	private void addComponents() {
		add(lblTrain);
		add(lblTrainName);
		add(txtTrainName);
		add(lblSourceStation);
		add(txtSourceStation);
		add(lblDestinationStation);
		add(txtDestinationStation);
		add(lblTrainCode);
		add(txtTrainCode);
		add(btnAddTrain);
		add(btnDisplayTrains);
		add(lblIntermediateStation);
		add(txtIntermediatestation);
		add(btnAddIntermediateStation);
		add(btnClear);
		add(btnFinish);
		add(lblArrivalTime);
		add(lblDepartureTime);
		add(lblSourceDepartureTime);
		add(lblDestinationArrivalTime);
		add(chSourceDepartureTimeHours);
		add(chSourceDepartureTimeMinutes);
		add(chDestinationArrivalTimeHours);
		add(chDestinationArrivalTimeMinutes);
		add(chArrivalTimeHours);
		add(chArrivalTimeMinutes);
		add(chDepartureTimeHours);
		add(chDepartureTimeMinutes);
		add(cbTues);
		add(cbWed);
		add(cbThurs);
		add(cbFri);
		add(cbMon);
		add(cbSat);
		add(cbSun);
		add(lblDays);
		add(chTimeDifference);
		add(lblTimeDifference);

		// add(chSourceStation);
		// add(chDestinationStation);
		// add(chIntermediateStation);
	}

	public void printTrainDetails(Train train) {
		String message = "";
		message = message + "Train Code :"
				+ String.valueOf(train.getTrainCode()) + "\n";
		message = message + "Train Name : " + train.getTrainName() + "\n";
		message = message + "Source Station : " + train.getSourceStation()
				+ "\n";
		message = message + "Source Departure Time : "
				+ train.getSourceDepartureTime() + "\n";
		message = message + "Destination Station : "
				+ train.getDestinationStation() + "\n";
		message = message + "Destination Arrival Time : "
				+ train.getDestinationArrivaltime() + "\n";

		message = message + "Intermediate Stations :";
		for (Integer i : train.getInBetweenStations()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Arrival Times:";
		for (String i : train.getArrivalTimes()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Departure Times:";
		for (String i : train.getDepartureTimes()) {
			message = message + i + " ";
		}
		message = message + "\n";

		message = message + "Running Days:";
		for (String i : train.getRunningDaysOfTheWeek()) {
			message = message + i + " ";
		}
		message = message + "\n";

		JOptionPane.showMessageDialog(null, message);
	}

	/* Function to validate the time */
	@SuppressWarnings("deprecation")
	boolean validateTime(ArrayList<String> arrivalTimes,
			ArrayList<String> departureTimes, String arrivalTime,
			String departureTime, String sdHours, String sdMinutes,
			String daHours, String daMinutes) {

		String arrivalTimeSplit[], departureTimeSplit[], arrivalTimeHour, arrivalTimeMin, departureTimeHour, departureTimeMin;
		Time tmArrivalTime, tmDepartureTime, tmSourceTime, tmDestinationTime;
		/* Splitting the time so that it is divided into hours and minutes */
		arrivalTimeSplit = arrivalTime.split(":");
		departureTimeSplit = departureTime.split(":");

		/* Assigning the hours and minutes to a Time variable */
		arrivalTimeHour = arrivalTimeSplit[0];
		arrivalTimeMin = arrivalTimeSplit[1];
		tmArrivalTime = new Time(Integer.parseInt(arrivalTimeHour),
				Integer.parseInt(arrivalTimeMin), 0);
		/**************************/

		/* Assigning the hours and minutes to a Time variable */
		departureTimeHour = departureTimeSplit[0];
		departureTimeMin = departureTimeSplit[1];
		tmDepartureTime = new Time(Integer.parseInt(departureTimeHour),
				Integer.parseInt(departureTimeMin), 0);
		/***********************/

		/* Making the source Departure Time and Destination Arrival Time */
		tmSourceTime = new Time(Integer.parseInt(sdHours),
				Integer.parseInt(sdMinutes), 0);
		tmDestinationTime = new Time(Integer.parseInt(daHours),
				Integer.parseInt(daMinutes), 0);

		/*
		 * Checking when the first arrival and departure time is added to the
		 * arraylist
		 */
		if (arrivalTimes.size() == 0 && departureTimes.size() == 0) {
			if (tmArrivalTime.getTime() <= tmSourceTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be less Source Departure Time");
				return true;
			}
			if (tmDepartureTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Departure Time cannot be moe than the Destatination Arrival Time");
				return true;
			}
			if (tmArrivalTime.getTime() >= tmDepartureTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be greater than departure time");
				return true;
			}
			if (tmSourceTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
		}
		/*
		 * Checking when the second onwards arrival and departure time is added
		 * to the arraylist
		 */
		else {
			if (tmSourceTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
			/*
			 * Look we know destination arrival time and we have arrival time
			 * and departure time Now we just need last departure time
			 */
			Time timeOfLastDeparture;
			@SuppressWarnings("unused")
			String lastDepartureTime[], h1, m1, h2, m2;
			/* Converting the last departure time into time */
			lastDepartureTime = listOfDepartureTimes.get(
					listOfDepartureTimes.size() - 1).split(":");
			h1 = lastDepartureTime[0];
			m1 = lastDepartureTime[1];
			timeOfLastDeparture = new Time(Integer.parseInt(h1),
					Integer.parseInt(m1), 0);
			if (tmArrivalTime.getTime() <= timeOfLastDeparture.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Arrival Time can't be less than previous departure time");
				return true;
			}
			if (tmDepartureTime.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Departure Time cannot be moe than the Destatination Arrival Time");
				return true;
			}
			if (tmArrivalTime.getTime() >= tmDepartureTime.getTime()) {
				JOptionPane.showMessageDialog(null,
						"Arrival Time can't be greater than departure time");
				return true;
			}
			if (timeOfLastDeparture.getTime() >= tmDestinationTime.getTime()) {
				JOptionPane
						.showMessageDialog(null,
								"Source Departure  Time can't be equal to Destination Arrival Time");
				return true;
			}
		}
		return false;
	}

	/* Function to validate the schedule */
	@SuppressWarnings({ "deprecation" })
	public boolean validateSchedule(String arrivalTime, String departureTime,
			int IntermediateStation, int SourceStation, int DestinationStation,
			ArrayList<Integer> listOfStationsAdded, String sdHours,
			String sdMinutes, String daHours, String daMinutes) {

		String arrivalTimeSplit[], departureTimeSplit[], arrivalTimeHour, arrivalTimeMin, departureTimeHour, departureTimeMin;
		@SuppressWarnings("unused")
		Time tmArrivalTime, tmDepartureTime, tmSourceDepartureTime, tmDestinationArrivalTime;
		/* So here we get the time difference upto 60 minutes */
		int timeDifference = Integer.parseInt(chTimeDifference
				.getSelectedItem());

		/* Splitting the time so that it is divided into hours and minutes */
		arrivalTimeSplit = arrivalTime.split(":");
		departureTimeSplit = departureTime.split(":");

		/* Assigning the hours and minutes to a Time variable */
		arrivalTimeHour = arrivalTimeSplit[0];
		arrivalTimeMin = arrivalTimeSplit[1];
		/* Arrival time of intermediate station */
		tmArrivalTime = new Time(Integer.parseInt(arrivalTimeHour),
				Integer.parseInt(arrivalTimeMin), 0);
		/**************************/

		/* Assigning the hours and minutes to a Time variable */
		departureTimeHour = departureTimeSplit[0];
		departureTimeMin = departureTimeSplit[1];
		/* Departure time of intermediate station */
		tmDepartureTime = new Time(Integer.parseInt(departureTimeHour),
				Integer.parseInt(departureTimeMin), 0);
		/***********************/

		/* Making the source Departure Time and Destination Arrival Time */
		tmSourceDepartureTime = new Time(Integer.parseInt(sdHours),
				Integer.parseInt(sdMinutes), 0);
		tmDestinationArrivalTime = new Time(Integer.parseInt(daHours),
				Integer.parseInt(daMinutes), 0);

		/*
		 * Condition for suppose the intermediate station is the first station
		 * to be added
		 */

		if (listOfStationsAdded.size() == 0) {
			/*
			 * if its the first station then calculate the track Between source
			 * and intermediate
			 */

			for (Integer i : trainGraph.keySet()) {
				Train tr = trainGraph.get(i);
				int j = 0;
				/*
				 * Case where ist two stations of train is same as 1st two
				 * stations of train to be added
				 */
				if (((tr.getSourceStation() == SourceStation && tr
						.getInBetweenStations().get(0) == IntermediateStation))
						&& validateDay(tr)) {
					/* Split the time */
					String str[] = tr.getSourceDepartureTime().split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getArrivalTimes().get(0)
							.split(":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime()
							- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						/*
						 * Enabling the textboxes which were disabled by Add
						 * Intermediate Station Button
						 */
						txtSourceStation.setEnabled(true);
						txtDestinationStation.setEnabled(true);
						chSourceDepartureTimeHours.setEnabled(true);
						chSourceDepartureTimeMinutes.setEnabled(true);
						chDestinationArrivalTimeHours.setEnabled(true);
						chDestinationArrivalTimeMinutes.setEnabled(true);
						chTimeDifference.setEnabled(true);
						return true;
					}
				}
				// JOptionPane.showMessageDialog(null, "adffdgdad");
				/*
				 * Case where last two stations of a train is same as the two
				 * station to be added for new train
				 */
				if (((tr.getInBetweenStations().get(
						tr.getInBetweenStations().size() - 1) == SourceStation && tr
						.getDestinationStation() == IntermediateStation))
						&& validateDay(tr)) {
					JOptionPane.showMessageDialog(
							null,
							"tr.in"
									+ tr.getInBetweenStations().get(
											tr.getInBetweenStations().get(
													tr.getInBetweenStations()
															.size())));
					/* split the time */
					String str[] = tr.getDepartureTimes()
							.get(tr.getDepartureTimes().size() - 1).split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getDestinationArrivaltime().split(
							":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime()
							- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where the two consective stations is in the intermediate
				 * stations
				 */
				for (j = 0; j < tr.getInBetweenStations().size() - 1; j++) {
					if (((tr.getInBetweenStations().get(j) == SourceStation && tr
							.getInBetweenStations().get(j + 1) == IntermediateStation))
							&& validateDay(tr)) {
						/* First ly I split the time */
						String str[] = tr.getDepartureTimes().get(j).split(":"), h1, m1;
						/* Now assigning hour and minute */
						h1 = str[0];
						m1 = str[1];
						/* Now creating the time */
						Time tm = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						/* String for arrival time */
						String strArrival[] = tr.getArrivalTimes().get(j + 1)
								.split(":");
						/* Now assigning hour and minute */
						h1 = strArrival[0];
						m1 = strArrival[1];
						/* Now creating the time */
						Time tmArrival = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						if ((Math.abs(tm.getTime()
								- tmSourceDepartureTime.getTime()) < timeDifference * 60 * 1000)
								|| (Math.abs(tmArrival.getTime()
										- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
							JOptionPane.showMessageDialog(
									null,
									"Timing Conflicts with "
											+ tr.getTrainName() + "("
											+ tr.getTrainCode() + ")");
							txtIntermediatestation.setText("");
							chArrivalTimeHours.select(0);
							chArrivalTimeMinutes.select(0);
							chDepartureTimeHours.select(0);
							chDepartureTimeMinutes.select(0);
							return true;
						}
					}
				}
			}
		}
		/* Condition for more than 1 intermediate station */
		else {
			// JOptionPane.showMessageDialog(null,
			// "Inside listof staions greater than zero");
			/*
			 * if its the first station then calculate the track Between source
			 * and intermediate
			 */

			for (Integer i : trainGraph.keySet()) {
				Train tr = trainGraph.get(i);
				int j = 0;
				/*
				 * Case where ist two stations of train is same as 1st two
				 * stations of train to be added
				 */
				if (tr.getSourceStation() == listOfStationsAdded
						.get(listOfStationsAdded.size() - 1)
						&& tr.getInBetweenStations().get(0) == IntermediateStation
						&& validateDay(tr)) {
					/* Split the time */
					String str[] = tr.getSourceDepartureTime().split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					/* Split the time */
					String str1[] = listOfDepartureTimes.get(
							listOfDepartureTimes.size() - 1).split(":");
					/* Now assigning hour and minute */
					h1 = str1[0];
					m1 = str1[1];
					/* Now creating the time */
					Time tm1 = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getArrivalTimes().get(0)
							.split(":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						listOfStationsAdded
								.remove(listOfStationsAdded.size() - 1);
						listOfArrivalTimes
								.remove(listOfArrivalTimes.size() - 1);
						listOfDepartureTimes
								.remove(listOfDepartureTimes.size() - 1);
						/* So that the label constantly changes */
						lblIntermediateStation
								.setText("Intermediate Station "
										+ String.valueOf(listOfStationsAdded
												.size() + 1));
						txtIntermediatestation.setText(String
								.valueOf(stations.get(listOfStationsAdded
										.size() + 1)));
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where last two stations of a train is same as the two
				 * station to be added for new train
				 */
				if (tr.getInBetweenStations()
						.get(tr.getInBetweenStations().size() - 1).intValue() == listOfStationsAdded
						.get(listOfStationsAdded.size() - 1).intValue()
						&& tr.getDestinationStation() == IntermediateStation
						&& validateDay(tr)) {
					// JOptionPane.showMessageDialog(null, "inside second if");
					/* First ly I split the time */
					String str[] = tr.getDepartureTimes()
							.get(tr.getDepartureTimes().size() - 1).split(":"), h1, m1;
					/* Now assigning hour and minute */
					h1 = str[0];
					m1 = str[1];
					/* Now creating the time */
					Time tm = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					/* First ly I split the time */
					String str1[] = listOfDepartureTimes.get(
							listOfDepartureTimes.size() - 1).split(":");
					/* Now assigning hour and minute */
					h1 = str1[0];
					m1 = str1[1];
					/* Now creating the time */
					Time tm1 = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);
					/* String for arrival time */
					String strArrival[] = tr.getDestinationArrivaltime().split(
							":");
					/* Now assigning hour and minute */
					h1 = strArrival[0];
					m1 = strArrival[1];
					/* Now creating the time */
					Time tmArrival = new Time(Integer.parseInt(h1),
							Integer.parseInt(m1), 0);

					if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
							|| (Math.abs(tmArrival.getTime()
									- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
						listOfStationsAdded
								.remove(listOfStationsAdded.size() - 1);
						listOfArrivalTimes
								.remove(listOfArrivalTimes.size() - 1);
						listOfDepartureTimes
								.remove(listOfDepartureTimes.size() - 1);
						/* So that the label constantly changes */
						lblIntermediateStation
								.setText("Intermediate Station "
										+ String.valueOf(listOfStationsAdded
												.size() + 1));
						txtIntermediatestation.setText(String
								.valueOf(stations.get(listOfStationsAdded
										.size() + 1)));
						JOptionPane.showMessageDialog(null,
								"Timing Conflicts with " + tr.getTrainName()
										+ "(" + tr.getTrainCode() + ")");
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						return true;
					}
				}
				/*
				 * Case where the two consective stations is in the intermediate
				 * stations
				 */
				for (j = 0; j < tr.getInBetweenStations().size() - 1; j++) {
					// JOptionPane
					// .showMessageDialog(
					// null,
					// String.valueOf(j)
					// + " "
					// + tr.getInBetweenStations().get(j)
					// + " "
					// + listOfStationsAdded
					// .get(listOfStationsAdded
					// .size() - 1)
					// + " "
					// + " "
					// + tr.getInBetweenStations().get(
					// j + 1) + " "
					// + IntermediateStation);
					int a = tr.getInBetweenStations().get(j);
					int b = listOfStationsAdded
							.get(listOfStationsAdded.size() - 1);
					int c = tr.getInBetweenStations().get(j + 1);
					int d = IntermediateStation;
					/*
					 * if (tr.getInBetweenStations().get(j) ==
					 * listOfStationsAdded .get(listOfStationsAdded.size() - 1)
					 * && tr.getInBetweenStations().get(j + 1) ==
					 * IntermediateStation)
					 */
					// System.out.println(a + b + c + d);
					if (a == b && c == d && validateDay(tr)) {
						// JOptionPane.showMessageDialog(null,
						// "inside third if");
						/* First ly I split the time */
						String str[] = tr.getDepartureTimes().get(j).split(":"), h1, m1;
						/* Now assigning hour and minute */
						h1 = str[0];
						m1 = str[1];
						/* Now creating the time */
						Time tm = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);

						/* First ly I split the time */
						String str1[] = listOfDepartureTimes.get(
								listOfDepartureTimes.size() - 1).split(":");
						/* Now assigning hour and minute */
						h1 = str1[0];
						m1 = str1[1];
						/* Now creating the time */
						Time tm1 = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);

						/* String for arrival time */
						String strArrival[] = tr.getArrivalTimes().get(j + 1)
								.split(":");
						/* Now assigning hour and minute */
						h1 = strArrival[0];
						m1 = strArrival[1];
						/* Now creating the time */
						Time tmArrival = new Time(Integer.parseInt(h1),
								Integer.parseInt(m1), 0);
						if ((Math.abs(tm.getTime() - tm1.getTime()) < timeDifference * 60 * 1000)
								|| (Math.abs(tmArrival.getTime()
										- tmArrivalTime.getTime()) < timeDifference * 60 * 1000)) {
							listOfStationsAdded.remove(listOfStationsAdded
									.size() - 1);
							listOfArrivalTimes
									.remove(listOfArrivalTimes.size() - 1);
							listOfDepartureTimes.remove(listOfDepartureTimes
									.size() - 1);
							/* So that the label constantly changes */
							lblIntermediateStation
									.setText("Intermediate Station "
											+ String.valueOf(listOfStationsAdded
													.size() + 1));
							JOptionPane.showMessageDialog(
									null,
									"Timing Conflicts with "
											+ tr.getTrainName() + "("
											+ tr.getTrainCode() + ")");
							txtIntermediatestation.setText("");
							chArrivalTimeHours.select(0);
							chArrivalTimeMinutes.select(0);
							chDepartureTimeHours.select(0);
							chDepartureTimeMinutes.select(0);
							return true;
						}
					}
				}
			}
		}

		return false;
	}

	public boolean validateDay(Train tr) {
		ArrayList<String> daySelected = new ArrayList<String>();

		if (cbMon.isSelected())
			daySelected.add(cbMon.getText());
		if (cbTues.isSelected())
			daySelected.add(cbTues.getText());
		if (cbWed.isSelected())
			daySelected.add(cbWed.getText());
		if (cbThurs.isSelected())
			daySelected.add(cbThurs.getText());
		if (cbFri.isSelected())
			daySelected.add(cbFri.getText());
		if (cbSat.isSelected())
			daySelected.add(cbSat.getText());
		if (cbSun.isSelected())
			daySelected.add(cbSun.getText());

		int index = 0;
		for (String i : tr.getRunningDaysOfTheWeek()) {
			// if (i.equalsIgnoreCase(daySelected.get(index))) {
			if (daySelected.contains(i)) {
				// JOptionPane.showMessageDialog(null, "days are same " + i +
				// " "
				// + daySelected.get(index));
				return true;
			}
			// index++;
		}
		return false;
	}

	/* To validate the text boxes which come under stations */
	private void textBoxesEventHandling() {

		txtSourceStation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtSourceStation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtSourceStation.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {
			}
		});

		txtDestinationStation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtDestinationStation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtDestinationStation.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtTrainCode.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {

			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtTrainCode.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtTrainCode.setText(str2);
					}
				} catch (Exception e1) {
				}

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		txtIntermediatestation.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				try {
					/* To get the key typed in that event */
					char ch = e.getKeyChar();
					/* To convert the character to a string */
					String str = String.valueOf(ch);
					try {
						/* To convert the string to an integer */
						@SuppressWarnings("unused")
						int x = Integer.parseInt(str);
					} catch (NumberFormatException nfe) {
						/*
						 * To get the entire text that was written in the text
						 * box
						 */
						String str1 = txtIntermediatestation.getText();
						/*
						 * To get the substring of the text using substr
						 * function till length-1
						 */
						String str2 = str1.substring(0, str1.length() - 1);
						/*
						 * To assign the new text to the textbox so that any
						 * character is not typed into the textbox
						 */
						txtIntermediatestation.setText(str2);
					}
				} catch (Exception e1) {
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});
	}

	/* To define the buttons */
	private void buttonEventHandling() {

		/* Event for Adding train */
		btnAddTrain.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				try {
					openDatabase();
					/*
					 * Do not allow the button to submit until button is not
					 * enabled
					 */
					if (enable == 1) {
						JOptionPane.showMessageDialog(null,
								"Train Information is incomplete");
						closeDatabase();
						return;
					}
					/*
					 * Condition to make sure the text boxes are filled before
					 * submitting
					 */
					if (txtTrainName.getText().equals("")
							|| txtTrainCode.getText().equals("")
							|| txtSourceStation.getText().equals("")
							|| txtDestinationStation.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All fields must be filled");
						closeDatabase();
						return;
					}

					if (cbMon.isSelected() == false
							&& cbTues.isSelected() == false
							&& cbWed.isSelected() == false
							&& cbThurs.isSelected() == false
							&& cbFri.isSelected() == false
							&& cbSat.isSelected() == false
							&& cbSun.isSelected() == false) {
						JOptionPane.showMessageDialog(null,
								"Atleast one day must be checked");
						closeDatabase();
						return;
					}

					if (txtSourceStation.getText().equals(
							txtDestinationStation.getText())) {
						JOptionPane.showMessageDialog(null,
								"Source is same as Destination");
						closeDatabase();
						return;
					}

					/* Condition for train to not repeat again once added */
					if (trainGraph.get(Integer.parseInt(txtTrainCode.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Train Already Exists");
						closeDatabase();
						return;
					}

					/*
					 * Code to see if Station1 and Station2 exists or not and
					 * store the input in an integer
					 */
					int sourceStation = Integer.parseInt(txtSourceStation
							.getText());
					int destStation = Integer.parseInt(txtDestinationStation
							.getText());

					/* Check whether both stations exist or not */
					if (stationGraph.get(sourceStation) == null
							&& stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Both Station do not exist");
						closeDatabase();
						return;
					}
					/* Check whether the next station is there not */
					if (stationGraph.get(sourceStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Source Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the previous station is there not */
					if (stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Destination Station does not exist");
						closeDatabase();
						return;
					}

					/*
					 * The create Graph method which would give source station
					 * and destination code as input and get the intermediate
					 * stations
					 */
					/*
					 * The code to add intermediate trains by adding shortest
					 * path
					 */

					/* Creating object of train */
					Train train = new Train();

					/*
					 * Inputting the Source destination train_name and train
					 * code
					 */
					train.setTrainName(txtTrainName.getText());
					train.setSourceStation(Integer.parseInt(txtSourceStation
							.getText()));
					train.setDestinationStation(Integer
							.parseInt(txtDestinationStation.getText()));
					train.setTrainCode(Integer.parseInt(txtTrainCode.getText()));
					/* Adding the starting time and ending time */
					train.setSourceDepartureTime(chSourceDepartureTimeHours
							.getSelectedItem()
							+ ":"
							+ chSourceDepartureTimeMinutes.getSelectedItem());
					train.setDestinationArrivaltime(chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem());
					train.setNoOfHalts(listOfStationsAdded.size() + 2);
					/*
					 * Adding the source and destination to the arraylist as the
					 * array list earlier contained only intermediate stations
					 * 
					 * listOfStationsAdded.add(0,
					 * Integer.parseInt(txtSourceStation.getText()));
					 * 
					 * listOfStationsAdded.add(listOfStationsAdded.size(),
					 * Integer.parseInt(txtDestinationStation.getText()));
					 */
					/*
					 * Adding the intermediate stations to the train's list of
					 * stations
					 */

					train.setInBetweenStations(listOfStationsAdded);
					/* Storing the set of arrival times and departure times */
					train.setArrivalTimes(listOfArrivalTimes);
					train.setDepartureTimes(listOfDepartureTimes);
					train.setRunningDaysOfTheWeek(runningDaysOfTheWeek);

					/* Printing the stations for a train */
					/*
					 * String message = ""; for (Integer i :
					 * listOfStationsAdded) message = message +
					 * String.valueOf(i) + " ";
					 * JOptionPane.showMessageDialog(null, message);
					 */

					/* Make the trainGraph */
					trainGraph.put(train.getTrainCode(), train);

					/* Refreshing the text boxes */
					txtTrainName.setText("");
					txtSourceStation.setText("");
					txtDestinationStation.setText("");
					txtTrainCode.setText("");
					txtIntermediatestation.setText("");
					/* refreshing the choices */
					chArrivalTimeHours.select(0);
					chArrivalTimeMinutes.select(0);
					chDepartureTimeHours.select(0);
					chDepartureTimeMinutes.select(0);
					chSourceDepartureTimeHours.select(0);
					chSourceDepartureTimeMinutes.select(0);
					chDestinationArrivalTimeHours.select(0);
					chDestinationArrivalTimeMinutes.select(0);
					chTimeDifference.select(2);
					/* Refreshing the checkbioxes */
					cbMon.setSelected(false);
					cbTues.setSelected(false);
					cbWed.setSelected(false);
					cbThurs.setSelected(false);
					cbFri.setSelected(false);
					cbSat.setSelected(false);
					cbSun.setSelected(false);
					/*****************************/

					/* Inserting into the OODB */
					insertIntoDatabase(train.getInBetweenStations());
					insertIntoDatabase(train.getArrivalTimes());
					insertIntoDatabase(train.getDepartureTimes());
					insertIntoDatabase(train.getRunningDaysOfTheWeek());

					insertIntoDatabase(train);
					printTrainDetails(train);
					/*
					 * Put this train into the station from where it is
					 * originating
					 */
					/***********************************/
					Station st = retrieveStationObject(sourceStation);
					st.getSourceTrains().add(train.getTrainCode());
					insertIntoDatabase(st.getSourceTrains());
					insertIntoDatabase(st);
					/**********************************/
					/*
					 * Put this train into the station to where it is ending
					 */
					/***********************************/
					st = retrieveStationObject(destStation);
					st.getDestinationTrains().add(train.getTrainCode());
					insertIntoDatabase(st.getDestinationTrains());
					insertIntoDatabase(st);
					/**********************************/
					/*
					 * Put this train into the station to where it is
					 * intermediate
					 */
					/**********************************/
					for (Integer i : listOfStationsAdded) {
						st = retrieveStationObject(i);
						st.getIntermediateTrains().add(train.getTrainCode());
						insertIntoDatabase(st.getIntermediateTrains());
						insertIntoDatabase(st);
					}
					/**********************************/
					/*
					 * It will enable the text boxes but at the same time
					 * disable the button
					 */
					txtTrainCode.setEnabled(true);
					txtTrainName.setEnabled(true);
					txtSourceStation.setEnabled(true);
					txtDestinationStation.setEnabled(true);
					txtIntermediatestation.setEnabled(true);
					/* Enabling the choices */
					chSourceDepartureTimeHours.setEnabled(true);
					chSourceDepartureTimeMinutes.setEnabled(true);
					chDestinationArrivalTimeHours.setEnabled(true);
					chDestinationArrivalTimeMinutes.setEnabled(true);
					chArrivalTimeHours.setEnabled(true);
					chArrivalTimeMinutes.setEnabled(true);
					chDepartureTimeHours.setEnabled(true);
					chDepartureTimeMinutes.setEnabled(true);
					chTimeDifference.setEnabled(true);
					/* Enabling the checkboxes */
					cbMon.setEnabled(true);
					cbTues.setEnabled(true);
					cbWed.setEnabled(true);
					cbThurs.setEnabled(true);
					cbFri.setEnabled(true);
					cbSat.setEnabled(true);
					cbSun.setEnabled(true);
					/*
					 * disabling the Addtrain Button and enabling the
					 * Addnexttrain button button after adding into the database
					 */
					enable = 1;
					/*
					 * Since the arraylist of stations was added so not it is
					 * cleared
					 */
					listOfStationsAdded = new ArrayList<Integer>();
					listOfArrivalTimes = new ArrayList<String>();
					listOfDepartureTimes = new ArrayList<String>();
					lblIntermediateStation.setText("Intermediate Station 1");

					closeDatabase();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		/* Event for Button Displaying Trains */
		btnDisplayTrains.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					String message = "";
					for (Integer var : getTrainGraph().keySet()) {

						message = message
								+ getTrainGraph().get(var).getTrainCode()
								+ ": "
								+ getTrainGraph().get(var).getTrainName() + " ";
						// printTrainDetails(getTrainGraph().get(var));
						/* Printing the source station */
						message = message + "|Src Stn "
								+ trainGraph.get(var).getSourceStation() + "| ";
						/********************************************************/
						if (trainGraph.get(var).getInBetweenStations().size() > 0)
							message = message + "|Int Stns " + " ";
						for (Integer j : trainGraph.get(var)
								.getInBetweenStations()) {
							message = message + " " + j;
						}
						if (trainGraph.get(var).getInBetweenStations().size() > 0)
							message = message + "| ";
						/********************************************************/
						/* Printing the destination station */
						message = message + "|Dst Stn "
								+ trainGraph.get(var).getDestinationStation()
								+ "| ";
						message = message + "\n";

					}

					JOptionPane.showMessageDialog(null, message);
				} catch (HeadlessException e) {
				}
			}
		});

		btnAddIntermediateStation.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					openDatabase();
					/* Don't allow any other station to be added */
					/*
					 * If Addnexttrain button is disabled and Addtrain is
					 * enabled then the following condition will be executed
					 */
					if (enable == 0) {
						JOptionPane.showMessageDialog(null,
								"No more stations can be added");
						closeDatabase();
						return;
					}
					/*
					 * Condition to make sure the text boxes are filled before
					 * submitting
					 */
					if (txtTrainName.getText().equals("")
							|| txtTrainCode.getText().equals("")
							|| txtSourceStation.getText().equals("")
							|| txtDestinationStation.getText().equals("")
							|| txtIntermediatestation.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"All fields must be filled");
						closeDatabase();
						return;
					}

					if (cbMon.isSelected() == false
							&& cbTues.isSelected() == false
							&& cbWed.isSelected() == false
							&& cbThurs.isSelected() == false
							&& cbFri.isSelected() == false
							&& cbSat.isSelected() == false
							&& cbSun.isSelected() == false) {
						JOptionPane.showMessageDialog(null,
								"Atleast one day must be checked");
						closeDatabase();
						return;
					}
					if (txtSourceStation.getText().equals(
							txtDestinationStation.getText())) {
						JOptionPane.showMessageDialog(null,
								"Source is same as Destination");
						closeDatabase();
						return;
					}

					/* Condition for train to not repeat again once added */
					if (trainGraph.get(Integer.parseInt(txtTrainCode.getText())) != null) {
						JOptionPane.showMessageDialog(null,
								"Train Already Exists");
						closeDatabase();
						return;
					}

					/*
					 * Code to see if Station1 and Station2 exists or not and
					 * store the input in an integer
					 */
					int sourceStation = Integer.parseInt(txtSourceStation
							.getText());
					int destStation = Integer.parseInt(txtDestinationStation
							.getText());
					int intermediateStation = Integer
							.parseInt(txtIntermediatestation.getText());
					String arrivalTime = chArrivalTimeHours.getSelectedItem()
							+ ":" + chArrivalTimeMinutes.getSelectedItem();
					String departureTime = chDepartureTimeHours
							.getSelectedItem()
							+ ":"
							+ chDepartureTimeMinutes.getSelectedItem();

					/* Check whether both stations exist or not */
					if (stationGraph.get(sourceStation) == null
							&& stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Both Station do not exist");
						closeDatabase();
						return;
					}
					/* Check whether the next station is there not */
					if (stationGraph.get(sourceStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Source Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the previous station is there not */
					if (stationGraph.get(destStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Destination Station does not exist");
						closeDatabase();
						return;
					}
					/* Check whether the intermediate station is there not */
					if (stationGraph.get(intermediateStation) == null) {
						JOptionPane.showMessageDialog(null,
								"Intermediate Station does not exist");
						closeDatabase();
						return;
					}

					if (intermediateStation == destStation) {
						/* Enable the other Addtrain buttton */
						JOptionPane
								.showMessageDialog(null,
										"Can't be added as an intermediate station as this is the destination station");
						closeDatabase();
						return;
					}

					/*
					 * Incase the station has already been added to the
					 * arraylist
					 */
					if (listOfStationsAdded.contains(intermediateStation)) {
						JOptionPane.showMessageDialog(null,
								"Intermediate Station has already been added");
						closeDatabase();
						return;
					}
					/*
					 * Incase the time for that particular station has already
					 * been added then throw the error
					 */
					if (listOfArrivalTimes.contains(arrivalTime)) {
						JOptionPane.showMessageDialog(null,
								"Arrival Time has already been added");
						closeDatabase();
						return;
					}
					/*
					 * Incase the departure time for that particular station has
					 * already been added then throw the error
					 */
					if (listOfDepartureTimes.contains(departureTime)) {
						JOptionPane.showMessageDialog(null,
								"Departure Time has already been added");
						closeDatabase();
						return;
					}

					/*
					 * Validate if the time is correct and consecutive returns
					 * true if not validating
					 */
					if (validateTime(listOfArrivalTimes, listOfDepartureTimes,
							arrivalTime, departureTime,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						closeDatabase();
						return;
					}

					/*
					 * Validation before adding a station to the train such that
					 * the track does not conflict
					 */
					// JOptionPane.showMessageDialog(null, "asda");
					if (validateSchedule(arrivalTime, departureTime,
							Integer.parseInt(txtIntermediatestation.getText()),
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()),
							listOfStationsAdded,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						txtIntermediatestation.setText(String
								.valueOf(stations.get(listOfStationsAdded
										.size() + 1)));
						// JOptionPane.showMessageDialog(null, "ashjhda");
						closeDatabase();
						return;
					}

					/*
					 * Time to disable the text boxes so that while intermediate
					 * stations are being added the textboxes are locked
					 */
					// JOptionPane.showMessageDialog(null,
					// "Befor disabling fields");
					txtTrainCode.setEnabled(false);
					txtTrainName.setEnabled(false);
					txtSourceStation.setEnabled(false);
					txtDestinationStation.setEnabled(false);
					chSourceDepartureTimeHours.setEnabled(false);
					chSourceDepartureTimeMinutes.setEnabled(false);
					chDestinationArrivalTimeHours.setEnabled(false);
					chDestinationArrivalTimeMinutes.setEnabled(false);
					chTimeDifference.setEnabled(false);
					/* Disabling the checkboxes */
					cbMon.setEnabled(false);
					cbTues.setEnabled(false);
					cbWed.setEnabled(false);
					cbThurs.setEnabled(false);
					cbFri.setEnabled(false);
					cbSat.setEnabled(false);
					cbSun.setEnabled(false);

					/***********************************/

					/* Validation for adding an intermediate station */
					if (listOfStationsAdded.size() == 0)
						/*
						 * if its the first station then calculate the distance
						 * Between source and intermediate
						 */
						track = retrieveTrackObject(sourceStation,
								intermediateStation);
					else
						/*
						 * if the list has 1 value means now compute the
						 * distance with the previous station
						 */
						track = retrieveTrackObject(listOfStationsAdded
								.get(listOfStationsAdded.size() - 1),
								intermediateStation);

					/*
					 * If there is no track then simply return a message saying
					 * track does not exist
					 */
					if (track == null) {
						JOptionPane.showMessageDialog(null,
								"Track does not exist");
						closeDatabase();
						return;
					} else {
						/*
						 * Write the validation for Arrival time and departure
						 * time that they must be consecutive so that before the
						 * intermediate station is added the time for arrival
						 * and departure from that station is verified
						 */
						// JOptionPane.showMessageDialog(null, "Track exists");
						listOfStationsAdded.add(intermediateStation);
						listOfArrivalTimes.add(arrivalTime);
						listOfDepartureTimes.add(departureTime);
						/*
						 * Running a for loop so that we could iterate over all
						 * the checkboxes and see which all are selected
						 */
						if (runningDaysOfTheWeek.size() == 0) {
							if (cbMon.isSelected())
								runningDaysOfTheWeek.add(cbMon.getText());
							if (cbTues.isSelected())
								runningDaysOfTheWeek.add(cbTues.getText());
							if (cbWed.isSelected())
								runningDaysOfTheWeek.add(cbWed.getText());
							if (cbThurs.isSelected())
								runningDaysOfTheWeek.add(cbThurs.getText());
							if (cbFri.isSelected())
								runningDaysOfTheWeek.add(cbFri.getText());
							if (cbSat.isSelected())
								runningDaysOfTheWeek.add(cbSat.getText());
							if (cbSun.isSelected())
								runningDaysOfTheWeek.add(cbSun.getText());
						}
						/* So that the label constantly changes */
						lblIntermediateStation.setText("Intermediate Station "
								+ String.valueOf(listOfStationsAdded.size() + 1));
						txtIntermediatestation.setText(String
								.valueOf(stations.get(listOfStationsAdded
										.size() + 1)));
						/* Displaying the list of stations */
						String message = "";
						for (Integer i : listOfStationsAdded) {
							message = message + String.valueOf(i) + " ";
						}
						// JOptionPane.showMessageDialog(null, message);

						/* Displaying the list of Arrival Times */
						message = "";
						for (String i : listOfArrivalTimes) {
							message = message + i + " ";
						}
						// JOptionPane.showMessageDialog(null, message);
						message = "";

						/* Displaying the list of Departure Times */
						message = "";
						for (String i : listOfDepartureTimes) {
							message = message + i + " ";
						}
						// JOptionPane.showMessageDialog(null, message);
						message = "";

						/*
						 * Making the textbox empty so that next intermediate
						 * station can be added
						 */
						txtIntermediatestation.setText("");
						chArrivalTimeHours.select(0);
						chArrivalTimeMinutes.select(0);
						chDepartureTimeHours.select(0);
						chDepartureTimeMinutes.select(0);
						JOptionPane.showMessageDialog(null,
								"Intermediate Station has been added");
						if (listOfStationsAdded.size() + 1 < stations.size() - 1)
							txtIntermediatestation.setText(String
									.valueOf(stations.get(listOfStationsAdded
											.size() + 1)));
						else{
							txtIntermediatestation.setEnabled(false);
							chArrivalTimeHours.setEnabled(false);
							chArrivalTimeMinutes.setEnabled(false);
							chDepartureTimeHours.setEnabled(false);
							chDepartureTimeMinutes.setEnabled(false);
						}
						closeDatabase();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		/*
		 * Clear button enable the intermediate train button and disable the
		 * addtrain button
		 */
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				/* 5 text boxes 8 choices 7 checkboxes 1 label */
				/* Clearing the 5 textfields */
				txtTrainName.setText("");
				txtSourceStation.setText("");
				txtDestinationStation.setText("");
				txtTrainCode.setText("");
				txtIntermediatestation.setText("");

				/* Clearing the 8 choices */
				chSourceDepartureTimeHours.select(0);
				chSourceDepartureTimeMinutes.select(0);
				chDestinationArrivalTimeHours.select(0);
				chDestinationArrivalTimeMinutes.select(0);
				chArrivalTimeHours.select(0);
				chArrivalTimeMinutes.select(0);
				chDepartureTimeHours.select(0);
				chDepartureTimeMinutes.select(0);
				chTimeDifference.select(2);

				/* Clearing the 7 check boxes */
				cbMon.setSelected(false);
				cbTues.setSelected(false);
				cbWed.setSelected(false);
				cbThurs.setSelected(false);
				cbFri.setSelected(false);
				cbSat.setSelected(false);
				cbSun.setSelected(false);

				/* Setting intermediate label to initial */
				lblIntermediateStation.setText("Intermediate Station 1");
				/*
				 * Code to unlock the text boxes in case the data entered is
				 * wrong
				 */
				txtTrainCode.setEnabled(true);
				txtTrainName.setEnabled(true);
				txtSourceStation.setEnabled(true);
				txtDestinationStation.setEnabled(true);
				txtIntermediatestation.setEnabled(true);

				/* Clearing the 8 choices */
				chSourceDepartureTimeHours.setEnabled(true);
				chSourceDepartureTimeMinutes.setEnabled(true);
				chDestinationArrivalTimeHours.setEnabled(true);
				chDestinationArrivalTimeMinutes.setEnabled(true);
				chArrivalTimeHours.setEnabled(true);
				chArrivalTimeMinutes.setEnabled(true);
				chDepartureTimeHours.setEnabled(true);
				chDepartureTimeMinutes.setEnabled(true);
				chTimeDifference.setEnabled(true);

				/* Clearing the 7 check boxes */
				cbMon.setEnabled(true);
				cbTues.setEnabled(true);
				cbWed.setEnabled(true);
				cbThurs.setEnabled(true);
				cbFri.setEnabled(true);
				cbSat.setEnabled(true);
				cbSun.setEnabled(true);

				enable = 1;
				/*
				 * Since we are clearing then we need to clear the intermediate
				 * stations
				 */
				listOfStationsAdded = new ArrayList<Integer>();
				listOfArrivalTimes = new ArrayList<String>();
				listOfDepartureTimes = new ArrayList<String>();
				runningDaysOfTheWeek = new ArrayList<String>();
			}
		});

		/*
		 * Finish button enables the Addtrain button and disables the
		 * Addnexttrain button
		 */
		btnFinish.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				openDatabase();

				if (enable == 0) {
					JOptionPane.showMessageDialog(null,
							"Station List has already been submitted");
					closeDatabase();
					return;
				}

				if (!txtIntermediatestation.getText().equals("")) {
					JOptionPane
							.showMessageDialog(null,
									"Click the Add Intermediate Station Button to Add an Intermediate Station");
					closeDatabase();
					return;
				}

				/* To check if any of the textbox is checked or not */
				if (cbMon.isSelected() == false && cbTues.isSelected() == false
						&& cbWed.isSelected() == false
						&& cbThurs.isSelected() == false
						&& cbFri.isSelected() == false
						&& cbSat.isSelected() == false
						&& cbSun.isSelected() == false) {
					JOptionPane.showMessageDialog(null,
							"Atleast one day must be checked");
					closeDatabase();
					return;
				}

				/*
				 * In case train is only between two stations then the arraylist
				 * of days will be vacant, so need to popoulate that
				 */

				if (runningDaysOfTheWeek.size() == 0) {
					/*
					 * Running a for loop so that we could iterate over all the
					 * checkboxes and see which all are selected
					 */
					if (cbMon.isSelected())
						runningDaysOfTheWeek.add(cbMon.getText());
					if (cbTues.isSelected())
						runningDaysOfTheWeek.add(cbTues.getText());
					if (cbWed.isSelected())
						runningDaysOfTheWeek.add(cbWed.getText());
					if (cbThurs.isSelected())
						runningDaysOfTheWeek.add(cbThurs.getText());
					if (cbFri.isSelected())
						runningDaysOfTheWeek.add(cbFri.getText());
					if (cbSat.isSelected())
						runningDaysOfTheWeek.add(cbSat.getText());
					if (cbSun.isSelected())
						runningDaysOfTheWeek.add(cbSun.getText());
				}

				/*
				 * If arraylist t is not empty we will see if last entry of
				 * arraylist is connected to the destination
				 */
				if (listOfStationsAdded.size() > 0) {

					String arrivalTime = chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem();
					String departureTime = chDestinationArrivalTimeHours
							.getSelectedItem()
							+ ":"
							+ chDestinationArrivalTimeMinutes.getSelectedItem();

					// String
					// arrivalTime=//listOfArrivalTimes.get(listOfArrivalTimes.size()-1);
					// String departureTime
					// =listOfDepartureTimes.get(listOfDepartureTimes.size()-1);

					/*
					 * I changed the first parameter from intermediate textbox
					 * to destination textbox
					 */
					if (validateSchedule(arrivalTime, departureTime,
							Integer.parseInt(txtDestinationStation.getText()),
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()),
							listOfStationsAdded,
							chSourceDepartureTimeHours.getSelectedItem(),
							chSourceDepartureTimeMinutes.getSelectedItem(),
							chDestinationArrivalTimeHours.getSelectedItem(),
							chDestinationArrivalTimeMinutes.getSelectedItem())) {
						chDestinationArrivalTimeHours.setEnabled(true);
						chDestinationArrivalTimeMinutes.setEnabled(true);
						closeDatabase();
						return;
					}
					String tmDestinationArrivalTime = Integer
							.parseInt(chDestinationArrivalTimeHours
									.getSelectedItem())
							+ ":"
							+ Integer.parseInt(chDestinationArrivalTimeMinutes
									.getSelectedItem());
					String departureTimeSplit[] = departureTime.split(":");

					// if (validateSchedule(
					// tmDestinationArrivalTime,
					// departureTime,
					// Integer.parseInt(txtDestinationStation.getText()),
					// listOfStationsAdded.get(listOfStationsAdded.size() - 1),
					// Integer.parseInt(txtDestinationStation.getText()),
					// listOfStationsAdded, departureTimeSplit[0],
					// departureTimeSplit[1],
					// chDestinationArrivalTimeHours.getSelectedItem(),
					// chDestinationArrivalTimeMinutes.getSelectedItem())) {
					// JOptionPane.showMessageDialog(null,
					// "Destination arrival is same");
					// closeDatabase();
					// return;
					// }

					track = retrieveTrackObject(listOfStationsAdded
							.get(listOfStationsAdded.size() - 1), Integer
							.parseInt(txtDestinationStation.getText()));
					if (track != null) {
						int x = JOptionPane.showConfirmDialog(null,
								"Do you want to add any more station");
						if (x == JOptionPane.NO_OPTION)
							enable = 0;
					} else {
						JOptionPane
								.showMessageDialog(null,
										"Source is not properly connected to the destination");
						closeDatabase();
						return;
					}
				}

				if (listOfStationsAdded.size() == 0) {

					track = retrieveTrackObject(
							Integer.parseInt(txtSourceStation.getText()),
							Integer.parseInt(txtDestinationStation.getText()));
					if (track != null) {
						int x = JOptionPane.showConfirmDialog(null,
								"Do you want to add any more station");
						if (x == JOptionPane.NO_OPTION)
							enable = 0;
					} else {
						JOptionPane
								.showMessageDialog(null,
										"Source is not properly connected to the destination");
						closeDatabase();
						return;

					}
				}
				txtTrainCode.setEnabled(false);
				txtTrainName.setEnabled(false);
				txtSourceStation.setEnabled(false);
				txtDestinationStation.setEnabled(false);
				txtIntermediatestation.setEnabled(false);

				chSourceDepartureTimeHours.setEnabled(false);
				chSourceDepartureTimeMinutes.setEnabled(false);
				chDestinationArrivalTimeHours.setEnabled(false);
				chDestinationArrivalTimeMinutes.setEnabled(false);
				chArrivalTimeHours.setEnabled(false);
				chArrivalTimeMinutes.setEnabled(false);
				chDepartureTimeHours.setEnabled(false);
				chDepartureTimeMinutes.setEnabled(false);

				chTimeDifference.setEnabled(false);
				/* Disabling the checkboxes */
				cbMon.setEnabled(false);
				cbTues.setEnabled(false);
				cbWed.setEnabled(false);
				cbThurs.setEnabled(false);
				cbFri.setEnabled(false);
				cbSat.setEnabled(false);
				cbSun.setEnabled(false);
				closeDatabase();
			}
		});
	}

	/* To add Components */

	public HashMap<Integer, Station> getStationGraph() {
		return stationGraph;
	}

	public void setStationGraph(HashMap<Integer, Station> stationGraph) {
		this.stationGraph = stationGraph;
	}

	public HashMap<Integer, Train> getTrainGraph() {
		return trainGraph;
	}

	public void setTrainGraph(HashMap<Integer, Train> trainGraph) {
		this.trainGraph = trainGraph;
	}

	public HashMap<Integer, Track> getTrackGraph() {
		return trackGraph;
	}

	public void setTrackGraph(HashMap<Integer, Track> trackGraph) {
		this.trackGraph = trackGraph;
	}

	public GUIPanel1 getGuiPanel() {
		return guiPanel1;
	}

	public void setGuiPanel(GUIPanel1 guiPanel) {
		this.guiPanel1 = guiPanel;
	}

	public ArrayList<Integer> getStations() {
		return stations;
	}

	public void setStations(ArrayList<Integer> stations) {
		this.stations = stations;
	}
}
